package com.qf.ps;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        //rabbitmq服务器安装的机器IP
        factory.setHost("localhost");
        //rabbitmq通过amqp协议连接时的端口号
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        //设置消息数据保存的虚拟主机,不同的虚拟主机彼此隔离
        factory.setVirtualHost("cdm");

        //获取connection对象
        Connection connection = factory.newConnection();
        //通过connection获取内部通道
        Channel channel = connection.createChannel();

        //声明交换机
        /*
            String exchange : 交换机名字（唯一）
            BuiltinExchangeType type ：交换机类型（工作模式不一样，选择对应的交换机类型）
            boolean durable： 是否持久化
            boolean autoDelete: 是否自动删除
            boolean internal: 是否是内部交换机
            Map<String, Object> arguments: 额外参数

            String exchange, BuiltinExchangeType type

            发布订阅模式不要求路由键，所以交换机类型是：FANOUT
         */
        channel.exchangeDeclare("psEx", BuiltinExchangeType.FANOUT);

        //声明2个队列
        channel.queueDeclare("psQue1",true,false,false,null);
        channel.queueDeclare("psQue2",true,false,false,null);

        //绑定交换机和队列的关系
        /*
            String queue: 队列名
            String exchange：交换机名
            String routingKey：路由键  FANOUT类型的交换机，不需要路由键
         */
        channel.queueBind("psQue1","psEx","");
        channel.queueBind("psQue2","psEx","");

        //发送消息
        channel.basicPublish("psEx","",null,("我是rabbitmq发送的第一条发布订阅消息:").getBytes(StandardCharsets.UTF_8));

        //释放资源
        channel.close();
        connection.close();
    }
}
